import { defineStore } from 'pinia';
import { api } from 'src/utils/axios';
import { signIn, getUserDetail,userNameIsStop } from 'src/api/user';
import { AxiosResponse } from 'axios';
import {
  is_token_valid,
  get_access_token,
  set_access_token,
  get_refresh_token,
  set_refresh_token, set_username } from 'src/utils/token'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    access_token: get_access_token(),
    refresh_token: get_refresh_token(),
  }),
  getters: {
    token_valid(): boolean {
      return this.access_token_valid || this.refresh_token_valid;
    },
    access_token_valid(): boolean {
      return is_token_valid(this.access_token);
    },
    refresh_token_valid(): boolean {
      return is_token_valid(this.refresh_token);
    },
  },
  actions: {
    get_valid_access_token(): Promise<string> {
      if (this.access_token_valid) {
        return Promise.resolve(this.access_token);
      }

      if (this.refresh_token_valid) {
        const refresh = this.refresh_token;
        return api
          .post('/api/token/refresh/', {
            refresh
          })
          .then((res) => {
            this.access_token = res.data.access;
            set_access_token(res.data.access);
            return res;
          })
          .then((res) => {
            return res.data.access;
          })
          .catch(() => {
            return Promise.reject('');
          })
      } else {
        return Promise.reject('');
      }
    },
    userIsStop(username: string): Promise<AxiosResponse> {
      return userNameIsStop({
        username,
      })
        .then((res) => {
          return Promise.resolve(res);
        });
    },
    signin(username: string, password: string): Promise<AxiosResponse> {
      return signIn({
          username,
          password,
        })
        .then((res) => {
          this.access_token = res.data.access;
        //   this.refresh_token = res.data.refresh;
          set_access_token(res.data.token);
          set_username(username)
        //   set_refresh_token(res.data.refresh);
          return Promise.resolve(res);
        });
    },
    signout(): Promise<void> {
      this.access_token = '';
      this.refresh_token = '';
      set_access_token('');
      set_refresh_token('');
      set_username('')
      return Promise.resolve();
    },
  },
});
